﻿using System;
using System.Data;
using BLL;
using DAL;
using Ext.Net;
using Roles;

namespace ERP.Modules
{
    public partial class User : System.Web.UI.UserControl
    {
        #region[Define]
        private static bool _flag;
        private DataTable _dtGetUser;
        private DataTable _dtGetUserEdit;
        private DataTable _dtGetGroupUser;
        private DataTable _dtGetGroupUserDetail;
        private DataTable _dtGetEmployee;
        private DataTable _dtGetEmployeeDetail;
        private DataTable _dtGetGroupUserFillter;
        private readonly BllUser _clsUser = new BllUser();
        private readonly BllEmployee _clsEmployee = new BllEmployee();
        private readonly BllGroupUser _clsGorupUser = new BllGroupUser();
        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                CheckPermisstion();
                GetUser();
                GetGroupUserFillter();
                btnEdit.Disable(true);
                btnDel.Disable(true);
                btnExport.Disable(true);
            }
        }
        //Store
        protected void StoreUser_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtSearch.Text = string.Empty;
            SelectBoxGroupUser.Text = string.Empty;
            GetUser();
            GetGroupUserFillter();
        }
        protected void StoreUserGroupUser_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtSearchUserGroupUserMain.Text = string.Empty;
            GetGroupUser();
        }
        protected void StoreUserEmployee_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtSearchUserEmployee.Text = string.Empty;
            GetEmployee();
        }
        //Button
        protected void btnAddNew_Click(object sender, DirectEventArgs e)
        {
            _flag = true;
            ClearText();
            WindowsUser.Show();
            txtGroupUserName.Focus(false, 100);
        }
        protected void btnEdit_Click(object sender, DirectEventArgs e)
        {
            var sm = grUser.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    _flag = false;
                    ClearText();
                    GetUserEdit(int.Parse(row.RecordID));
                    WindowsUser.Show();
                }
        }
        protected void btnDel_Click(object sender, DirectEventArgs e)
        {
            var sm = grUser.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    try
                    {
                        var obj = new EtUser { UsersId = int.Parse(row.RecordID) };
                        BllUser.Delete(obj);
                        if (obj.msg == 0)
                            HTML.clsFormat.Alert_ERROR("Thông Báo",
                                "Tên đăng nhập đang được sử dụng, không xoá được vui lòng thoát tên tăng nhập trước khi xoá !");

                    }
                    catch (Exception ex)
                    {
                        HTML.clsFormat.Alert_ERROR("Thông Báo", ex.Message);
                    }
                }
            GetUser();
        }
        protected void btnSavePopUp_Click(object sender, DirectEventArgs e)
        {
            Insert();
        }
        protected void btnCancelPopUp_Click(object sender, DirectEventArgs e)
        {
            WindowsUser.Close();
        }
        protected void btnAddGroupUser_Click(object sender, DirectEventArgs e)
        {
            txtSearchUserGroupUserMain.Text = string.Empty;
            GetGroupUser();
            WindowUserGroupUser.Show();
        }
        protected void btnAddEmployee_Click(object sender, DirectEventArgs e)
        {
            txtSearchUserEmployee.Text = string.Empty;
            GetEmployee();
            WindowUserEmployee.Show();
        }
        //Double-Click
        protected void UserDblClick(object sender, DirectEventArgs e)
        {
            _flag = false;
            ClearText();
            int Users_Id = int.Parse(e.ExtraParams["Users_Id"]);
            GetUserEdit(Users_Id);
            WindowsUser.Show();
        }
        //Search
        protected void Search_Event(object sender, DirectEventArgs e)
        {
            DataTable dtSearch = _clsUser.GetUser(txtSearch.Text);
            if (dtSearch != null && dtSearch.Rows.Count > 0)
            {
                StoreUser.DataSource = dtSearch;
                StoreUser.DataBind();
            }
            else
            {
                grUser.GetStore().RemoveAll();
            }
        }
        protected void SearchUserGorupUser_Event(object sender, DirectEventArgs e)
        {
            DataTable dtSearch = _clsGorupUser.GetGroupUser(txtSearchUserGroupUserMain.Text);
            if (dtSearch != null && dtSearch.Rows.Count > 0)
            {
                StoreUserGroupUser.DataSource = dtSearch;
                StoreUserGroupUser.DataBind();
            }
            else
            {
                grUserGroupUser.GetStore().RemoveAll();
            }
        }
        protected void SearchUserEmployee_Event(object sender, DirectEventArgs e)
        {
            DataTable dtSearch = _clsEmployee.GetEmployee(txtSearchUserEmployee.Text);
            if (dtSearch != null && dtSearch.Rows.Count > 0)
            {
                StoreUserEmployee.DataSource = dtSearch;
                StoreUserEmployee.DataBind();
            }
            else
            {
                grUserEmployee.GetStore().RemoveAll();
            }
        }

        //Cell-Click
        protected void UserEmployee_Click(object sender, DirectEventArgs e)
        {
            var sm = grUserEmployee.GetSelectionModel() as CellSelectionModel;
            if (sm != null)
            {
                var id = sm.SelectedCell.RecordID;
                GetEmployeeDetail(int.Parse(id));
            }
            if (sm != null)
            {
                sm.Clear();
                sm.UpdateSelection();
            }
            WindowUserEmployee.Close();
        }
        protected void UserGorupUser_Click(object sender, DirectEventArgs e)
        {
            var sm = grUserGroupUser.GetSelectionModel() as CellSelectionModel;
            if (sm != null)
            {
                var id = sm.SelectedCell.RecordID;
                GetGroupUserDetail(int.Parse(id));
            }
            if (sm != null)
            {
                sm.Clear();
                sm.UpdateSelection();
            }
            WindowUserGroupUser.Close();
        }
        //Select-Box
        protected void SelectBoxGroupUser_Change(object sender, DirectEventArgs e)
        {
            GetUser();
        }
        #endregion

        #region[Method]
        private void GetUser()
        {
            if (SelectBoxGroupUser.Text == string.Empty)
            {
                _dtGetUser = _clsUser.GetUser(txtSearch.Text);
                if (_dtGetUser != null && _dtGetUser.Rows.Count > 0)
                {
                    StoreUser.DataSource = _dtGetUser;
                    StoreUser.DataBind();
                }
                else
                {
                    grUser.GetStore().RemoveAll();
                }
            }
            else
            {
                _dtGetUser = _clsUser.GetUserFillter(int.Parse(SelectBoxGroupUser.SelectedItem.Value));
                if (_dtGetUser != null && _dtGetUser.Rows.Count > 0)
                {
                    StoreUser.DataSource = _dtGetUser;
                    StoreUser.DataBind();
                }
                else
                {
                    grUser.GetStore().RemoveAll();
                }
            }
        }
        private void GetUserEdit(int id)
        {
            _dtGetUserEdit = _clsUser.GetUserEdit(id);
            if (_dtGetUserEdit != null && _dtGetUserEdit.Rows.Count > 0)
            {
                hdIDUser.Text = _dtGetUserEdit.Rows[0]["Users_Id"].ToString();
                hdIDEmployee.Text = _dtGetUserEdit.Rows[0]["Employee_Id"].ToString();
                hdIDGroupUser.Text = _dtGetUserEdit.Rows[0]["USer_Detail_Id"].ToString();
                hdPasswords.Text = _dtGetUserEdit.Rows[0]["Passwords"].ToString();
                txtGroupUserName.Text = _dtGetUserEdit.Rows[0]["Group_Name"].ToString();
                txtEmployeeName.Text = _dtGetUserEdit.Rows[0]["FullName"].ToString();
                txtUserName.Text = _dtGetUserEdit.Rows[0]["UserName"].ToString();
                txtPassword.Text = _dtGetUserEdit.Rows[0]["Passwords"].ToString();
                txtNote.Text = _dtGetUserEdit.Rows[0]["Note"].ToString();
                if ((bool)_dtGetUserEdit.Rows[0]["IsActive"])
                {
                    chkLock.Checked = true;
                }
                else
                {
                    chkLock.Checked = false;
                }
            }
        }
        private void GetEmployee()
        {
            _dtGetEmployee = _clsEmployee.GetEmployee(txtSearchUserEmployee.Text);
            if (_dtGetEmployee != null && _dtGetEmployee.Rows.Count > 0)
            {
                StoreUserEmployee.DataSource = _dtGetEmployee;
                StoreUserEmployee.DataBind();
            }
            else
            {
                grUserEmployee.GetStore().RemoveAll();
            }
        }
        private void GetEmployeeDetail(int id)
        {
            _dtGetEmployeeDetail = _clsEmployee.GetEmployeeEdit(id);
            if (_dtGetEmployeeDetail != null && _dtGetEmployeeDetail.Rows.Count > 0)
            {
                hdIDEmployee.Text = _dtGetEmployeeDetail.Rows[0]["Employee_Id"].ToString();
                txtEmployeeName.Text = _dtGetEmployeeDetail.Rows[0]["FullName"].ToString();
            }
        }
        private void GetGroupUser()
        {
            _dtGetGroupUser = _clsGorupUser.GetGroupUser(txtSearchUserGroupUserMain.Text);
            if (_dtGetGroupUser != null && _dtGetGroupUser.Rows.Count > 0)
            {
                StoreUserGroupUser.DataSource = _dtGetGroupUser;
                StoreUserGroupUser.DataBind();
            }
            else
            {
                grUserGroupUser.GetStore().RemoveAll();
            }
        }
        private void GetGroupUserDetail(int id)
        {
            _dtGetGroupUserDetail = _clsGorupUser.GetGroupUserEdit(id);
            if (_dtGetGroupUserDetail != null && _dtGetGroupUserDetail.Rows.Count > 0)
            {
                hdIDGroupUser.Text = _dtGetGroupUserDetail.Rows[0]["Group_Id"].ToString();
                txtGroupUserName.Text = _dtGetGroupUserDetail.Rows[0]["Group_Name"].ToString();
            }
        }
        private void GetGroupUserFillter()
        {
            _dtGetGroupUserFillter = _clsGorupUser.GetGroupUser(string.Empty);
            if (_dtGetGroupUserFillter != null && _dtGetGroupUserFillter.Rows.Count > 0)
            {
                StoreGroupUser.DataSource = _dtGetGroupUserFillter;
                StoreGroupUser.DataBind();
            }
            else
            {
                SelectBoxGroupUser.GetStore().RemoveAll();
            }
        }
        private bool CheckInsert()
        {
            var check = false;
            var dtCheck = _clsUser.GetUser(string.Empty);
            if (dtCheck != null && dtCheck.Rows.Count > 0)
            {
                foreach (DataRow dr in dtCheck.Rows)
                {
                    if (hdIDUser.Text != dr["Users_Id"].ToString())
                    {
                        if (txtUserName.Text == dr["UserName"].ToString())
                        {
                            check = true;
                            HTML.clsFormat.Alert_ERROR("Thông Báo",
                                "Tên đăng nhập " + txtUserName.Text + " đã tồn tại !");
                        }
                    }
                }
            }
            return check;
        }
        private void Insert()
        {
            if (_flag)
            {
                InsertValue();
            }
            else
            {
                if (CheckPermisstionDobclick())
                {
                    HTML.clsFormat.Alert_ERROR("Thông Báo", "Bạn không được cấp quyền để sửa đổi !");
                }
                else
                {
                    UpdateValue();
                }
            }
        }
        private void InsertValue()
        {
            try
            {
                var obj = new EtUser
                {
                    UserName = txtUserName.Text,
                    Passwords = Encode.Encode.GetMD5(txtPassword.Text).ToUpper(),
                    USerDetailId = int.Parse(hdIDGroupUser.Text),
                    EmployeeId = int.Parse(hdIDEmployee.Text),
                    IsActive = chkLock.Checked,
                    IsUsed = false,
                    Note = txtNote.Text
                };
                BllUser.Insert(obj);
                if (obj.msg == 0)
                {
                    HTML.clsFormat.Alert_ERROR("Thông Báo", "Tên người dùng " + txtUserName.Text + " này đã tồn tại !");
                }
                else
                {
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Thêm người dùng thành công !");
                    GetUser();
                    ClearText();
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void UpdateValue()
        {
            try
            {
                if (!CheckInsert())
                {
                    if (txtPassword.Text == hdPasswords.Text)
                    {
                        var obj = new EtUser
                        {
                            UsersId = int.Parse(hdIDUser.Text),
                            UserName = txtUserName.Text,
                            Passwords = hdPasswords.Text,
                            USerDetailId = int.Parse(hdIDGroupUser.Text),
                            EmployeeId = int.Parse(hdIDEmployee.Text),
                            IsActive = chkLock.Checked,
                            Note = txtNote.Text
                        };
                        BllUser.Update(obj);
                        HTML.clsFormat.Alert_INFO("Thông Báo", "Cập nhật người dùng thành công !");
                        WindowsUser.Close();
                        GetUser();
                    }
                    else
                    {
                        var obj = new EtUser
                        {
                            UsersId = int.Parse(hdIDUser.Text),
                            UserName = txtUserName.Text,
                            Passwords = Encode.Encode.GetMD5(txtPassword.Text).ToUpper(),
                            USerDetailId = int.Parse(hdIDGroupUser.Text),
                            EmployeeId = int.Parse(hdIDEmployee.Text),
                            IsActive = chkLock.Checked,
                            Note = txtNote.Text
                        };
                        BllUser.Update(obj);
                        HTML.clsFormat.Alert_INFO("Thông Báo", "Cập nhật người dùng thành công !");
                        WindowsUser.Close();
                        GetUser();
                    }
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        #endregion

        #region[Clear-Text]
        private void ClearText()
        {
            hdIDGroupUser.Text = string.Empty;
            hdIDUser.Text = string.Empty;
            hdIDEmployee.Text = string.Empty;
            txtUserName.Text = string.Empty;
            txtPassword.Text = string.Empty;
            txtGroupUserName.Text = string.Empty;
            txtEmployeeName.Text = string.Empty;
            chkLock.Checked = false;
        }
        #endregion

        #region[Permisstion]
        private void CheckPermisstion()
        {
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.UserManager, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnAdd == false)
                {
                    btnAddNew.Visible = false;
                }
                if (Is_BtnEdit == false)
                {
                    btnEdit.Visible = false;
                }
                if (Is_BtnView == false)
                {
                    PanelUserMain.Visible = false;
                }
                if (Is_BtnDel == false)
                {
                    btnDel.Visible = false;
                }
                if (Is_BtnPrint == false)
                {
                    btnExport.Visible = false;
                }
            }
        }
        private bool CheckPermisstionDobclick()
        {
            var check = false;
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.UserManager, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnEdit == false)
                {
                    check = true;
                }
            }
            return check;
        }
        #endregion
    }
}